package org.scmpatrol.persistence.entity;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.scmpatrol.persistence.SCM;
import org.scmpatrol.scm.SCMCommit;
import org.scmpatrol.scm.SCMRepository;

@Stateless
@Local(SCM.class)
public class SCMBean implements SCM {
	transient final static Logger LOGGER = Logger.getLogger(SCMBean.class
			.getName());

	@PersistenceContext
	EntityManager manager;

	@Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)    
	public Long saveCommit(SCMCommit commit) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Saving commit " + commit);
		}
		manager.persist(commit);
		return commit.getId();
	}

	@Override
	public SCMCommit getCommit(Long revisionId) {
		LOGGER.debug("Getting commit " + revisionId);
		SCMCommit commit = manager.find(SCMCommit.class, revisionId);
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Loaded Commit " + commit);
		}
		return commit;
	}

	@Override
	public String getLastScmRevisionId(Long repositoryId) {
		LOGGER.debug("Getting last revision for repository " + repositoryId);
		Query query = manager.createNamedQuery("max_revision");
		query.setParameter("repositoryId", repositoryId);

		Long id = (Long) query.getSingleResult();
        if (id != null) {
            SCMCommit commit = getCommit(id);

            LOGGER.debug("Last revision number = " + commit.getScmRevision());
            return commit.getScmRevision();
        } else {
            return null;
        }
	}

	@Override
	public SCMRepository getRepository(Long id) {
		LOGGER.debug("Searching for repository " + id);
		SCMRepository repository = manager.find(SCMRepository.class, id);
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Repository " + id + " : " + repository);
		}
		return repository;
	}

	@Override
	public Long saveRepository(SCMRepository repository) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Saving repository " + repository);
		}
		manager.persist(repository);
		LOGGER.debug("Repository created with id " + repository.getId());
		return repository.getId();
	}

	@Override
	public List<SCMRepository> getRepositories() {
		LOGGER.debug("Getting all repositories");
		Query query = manager.createNamedQuery("all");
		List<SCMRepository> repositories = (List<SCMRepository>) query.getResultList(); 
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Number of found repositories : " + repositories.size());
		}
		return repositories;
	}
}
